package com.mk.cloud.common.util;

import act.app.ActionContext;
import com.mk.cloud.common.enums.GlobalValues;
import org.osgl.http.H;
import org.osgl.util.S;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * COOkie 防篡改机制
 */
public class CookieUtil {
    private static final String KEY = "hhhh-iiiii-vvvvvv-kkkkk";
    private static final String SPLIT = "^_^";
    private static final String PATH = "/";

    public static void addCookie(String key, String value, H.Response resp) {
        if (S.isNotBlank(value)) {
            String randomKey = S2.UUID();
            String saveTime = System.currentTimeMillis() + "";
            String signToken = EncyUtils.MD5(key, KEY, saveTime, randomKey, value);
            String cookieValue = signToken + SPLIT + saveTime + SPLIT + randomKey + SPLIT + value;
            try {
                resp.addCookie(new H.Cookie(
                    key,
                    Base64.getEncoder().encodeToString(cookieValue.getBytes(GlobalValues.CHARSET_UTF8.value()))
                ).path(PATH));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            resp.addCookie(new H.Cookie(
                    key,
                null).path(PATH));
        }
    }

    public static String getCookie(String key, ActionContext context) {
        H.Cookie uesr_cookie = context.cookie(key);
        if (uesr_cookie != null && S.isNotBlank(uesr_cookie.value())) {
            try {
                String cookie = new String(Base64.getDecoder().decode(uesr_cookie.value()),GlobalValues.CHARSET_UTF8.value());
                if (S.isNotBlank(cookie)) {
                    S.List cookieStrings = S.fastSplit(cookie, SPLIT);
                    if (cookieStrings.size() == 4) {
                        String signToken = cookieStrings.get(0);
                        String saveTime = cookieStrings.get(1);
                        String randomKey = cookieStrings.get(2);
                        String value = cookieStrings.get(3);
                        String sign = EncyUtils.MD5(key, KEY, saveTime, randomKey, value);
                        if (S.eq(sign, signToken)) {
                            return value;
                        }
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
